export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['欢迎归来']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {
  }
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj (obj) {
  if (!(typeof obj === 'object')) {
    return
  }

  for (var key in obj) {
    if (obj.hasOwnProperty(key) &&
      (obj[key] == null || obj[key] === undefined || obj[key] === '')) {
      delete obj[key]
    }
  }
  return obj
}

/**
 * 把o2对象复制到o1对象中
 * @param o1
 * @param o2
 * @returns {boolean}
 */
export function objToOverride (o1, o2) {
  if (o2 !== undefined) {
    Object.keys(o2).forEach(key => {
      if (o2[key] !== undefined) {
        o1[key] = o2[key]
      }
    })
  }
  return true
}

/**
 * o 的所有属性修改为undefined
 * @param o1
 * @returns {boolean}
 */
export function objToReset (o) {
  // eslint-disable-next-line no-return-assign
  Object.keys(o).forEach(key => {
    if (Array.isArray(o[key])) {
      o[key] = []
    } else {
      o[key] = undefined
    }
  })
  return true
}

/**
 *数组相剪
 * @param a
 * @param b
 * @returns {*}
 */
export function arrSubtraction (a, b) {
  if (Array.isArray(a) && Array.isArray(b)) {
    return a.filter((i) => !b.includes(i))
  }
  throw new new TypeError('arguments must be array')()
}

